package com.java.huxb.day03.utils;

import com.java.huxb.day03.entity.People;

import java.lang.reflect.Method;
import java.util.*;

/**
 * @author huxb
 * @date 2020/3/3 0003 下午 9:01
 */
public class SetUserNameUtil {

    public static  void  setUserName(List list, String getUserIdMethodName, String setUserNameMethodName){
        if (list.size() > 0) {
            Class<?> aClass = list.get(0).getClass();
            try {
                Method getUserIdMethod = aClass.getMethod(getUserIdMethodName);
                Method setUserNameMethod = aClass.getMethod(setUserNameMethodName, String.class);

                Set<String> userIdSet = new HashSet<>(list.size());
                for (Object obj : list) {
                    String userId = (String) getUserIdMethod.invoke(obj);
                    userIdSet.add(userId);
                }

                List<People> peopleList = PeopleUtils.getPeopleList(new ArrayList<>(userIdSet));
                if (peopleList.size() > 0) {
                    for (Object objTemp : list) {
                       String userIdTemp =(String) getUserIdMethod.invoke(objTemp);
                        People peopleTemp = peopleList.stream().filter(people -> userIdTemp.equals(people.getUserId())).findFirst().orElse(null);
                        if (peopleTemp != null) {
                            setUserNameMethod.invoke(objTemp, peopleTemp.getUserName());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }
}
